package com.nlecloud.bc.util;

import org.springframework.util.DigestUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author warrior
 * @description md5工具类
 */
public class MD5Util {

    /**
     * 获取url文件md5值
     *
     * @param fileUrl 文件url
     * @return
     */
    public static String getUrlFileMd5(String fileUrl) throws IOException {
        URL url = new URL(fileUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setConnectTimeout(3 * 1000);
        connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.110 Safari/537.36");
        InputStream inputStream = connection.getInputStream();
        String md5 = DigestUtils.md5DigestAsHex(inputStream);
        return md5;
    }

    public static String getFileMd5(String filePath) throws IOException {
        InputStream inputStream = new FileInputStream(new File(filePath));
        String md5 = DigestUtils.md5DigestAsHex(inputStream);
        return md5;
    }

    public static void main(String[] args) throws IOException {
       String digestStr = MD5Util.getFileMd5("C:\\Users\\83980\\Desktop\\fsdownload\\测试文件.zip");
       System.out.println(digestStr);
    }
}
